import { computed, reactive, ref, watch, unref, isRef } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import { omit, merge } from 'lodash-es';

export function useFormData({ props }) {
  
  const schemas = isRef(props.schemas) ? props.schemas.value : props.schemas;
  const defaultModel = {};
  schemas.forEach(({ dataIndex, defaultValue }) => {
    if (defaultValue !== undefined) {
      defaultModel[dataIndex] = defaultValue;
    }
  });
  const model = {
    ...defaultModel,
    ...(props?.model || {}),
  };
  const formState = reactive(model || {});
  return {
    formState,
  };
}

export function useFormState({ props, tableMethods, formState }) {
  
  const schemas = isRef(props.schemas) ? props.schemas.value : props.schemas;
  const getFormProps = computed(() => {
    const formProps = omit(props, ['model']);
    return formProps;
  });

  const { formRef, onReset, onFinish } = tableMethods;

  const getColProps = computed(() => {
    return props?.span || 24;
  });

  const getActionColProps = computed(() => {
    const formSchemas = schemas.filter(
      (schema) => schema.component !== 'Actions'
    );
    const span = props?.span || 24;
    const column = 24 / span;
    const offset = column - (formSchemas.length % column) - 1;
    const type = props?.type;
    return type === 'inline'
      ? {
        span,
        offset: offset * span,
      }
      : {
        span: 24,
      };
  });

  const getSchemas = computed(() => {
    return schemas.filter((schema) => schema.component !== 'Actions');
  });
  const getSchemaAction = computed(() => {
    return schemas.find((schema) => schema.component === 'Actions');
  });

  const getActionProps = (action) => {
    if (action.actionType === 'reset') {
      return merge(action, {
        onClick: onReset,
      });
    }
    if (action.actionType === 'submit') {
      return merge(action, {
        htmlType: 'submit',
      });
    }
    return omit(action);
  };

  return {
    getFormProps,
    getColProps,
    getActionColProps,
    getSchemas,
    getSchemaAction,
    getActionProps,
  };
}

export function useTableMethods({ props, emit }) {
  const formRef = ref<FormInstance | null>(null);
  // watch(formRef, () => {
  //   if (props?.ref) {
  //     props.ref = formRef.value;
  //   }
  // });

  const onReset = () => {
    formRef.value?.resetFields();
    emit('reset');
  };

  const onFinish = () => {
    formRef.value.validate().then((values) => {
      emit('finish', values);
    });
  };

  return {
    formRef,
    onReset,
    onFinish,
  };
}
